package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }


    /**
     *String 转 Date
     * yyyy-MM-dd HH:mm:ss
     * */
    public static Date stringToDate(String string) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(string);
        } catch (ParseException e) {
            return new Date();
        }
    }

    /**
     * String转Date
     * yyyy-MM-dd 年月日格式
     * */
    public static Date stringToDateYmd(String string) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(string);
        } catch (ParseException e) {
            return new Date();
        }
    }

    /**
     * Date 转 String
     * yyyy-MM-dd
     * */
    public static String DateToString(Date date){
        //Date类型转String  //可指定任意的返回格式  yyyy
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String dateString = sdf.format(date);
        System.out.println(dateString);
        return dateString;
    }


    /**
     * 给时间加天数
     * */
    public static  Date addTime(Date time,int amount){
        Date date =new Date();
        // 获取当前时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(time);
// 把日期往后增加一天,整数  往后推,负数往前移动
        calendar.add(calendar.DATE, amount);
// 这个时间就是日期往后推一天的结果
        date=calendar.getTime();
        return date;
    }

    /**
     * 给时间减天数
     * */

    public static  Date reductionTime(Date time,int amount){
        Date date =new Date();
        // 获取当前时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(time);
// 把日期往后增加一天,整数  往后推,负数往前移动
        calendar.add(calendar.DATE, -amount);
// 这个时间就是日期往后推一天的结果
        date=calendar.getTime();
        return date;
    }


    /**
     *计算两个日期之间相差的天数
     * */
    public static String countDays(String startTime,String endTime1){
        DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Long days =null;
        try {
            Date star = dft.parse(startTime);//开始时间
            Date endDay=dft.parse(endTime1);//结束时间
            Long starTime=star.getTime();
            Long endTime=endDay.getTime();
            Long num=endTime-starTime;//时间戳相差的毫秒数
            System.out.println("相差天数为："+num/24/60/60/1000);//除以一天的毫秒数
            days =num/24/60/60/1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days.toString();
    }

    /**获取当前月第一天*/
    public static  String monthFirstDay(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        return first;
    }

    /**获取当前月最后一天*/
    public static  String monthLastDay(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = format.format(ca.getTime());
        return last;
    }

    /**
     * 根据指定月份第一天
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getFirstDayOfMonth(int year,int month)
    {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR,year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        return cal.getTime();
    }

    /**
     * 获取某月的最后一天 如201712结果为2017-12-30
     * @param year
     * @param month
     * @return
     */
    public  static String getLastday(int year,int month){
        LocalDate firstDayOfCurrentDate = LocalDate.of(year, month, 1);
        LocalDate lastDayOfCurrentDate = firstDayOfCurrentDate.with(TemporalAdjusters.lastDayOfMonth());
        return lastDayOfCurrentDate.toString();
    }


    /**
     * 根据毫秒值计算倒计时，包含天数
     * @param millis 相差毫秒值
     * @return 返回倒计时，millis 小于等于0 返回：0天0小时0分钟0秒
     */
    public static String countdownWithDay(long millis){
        if (millis <= 0) {
            return "0天0小时0分钟0秒";
        }
        Duration duration = Duration.ofMillis(millis);
        long days =  duration.getSeconds() / XkTimeConstant.SECONDS_PER_DAY;
        int hours =  (int) ((duration.getSeconds() % XkTimeConstant.SECONDS_PER_DAY) / XkTimeConstant.SECONDS_PER_HOUR);
        int minutes = (int) ((duration.getSeconds() % XkTimeConstant.SECONDS_PER_HOUR) / XkTimeConstant.SECONDS_PER_MINUTE);
        int seconds = (int) (duration.getSeconds() % XkTimeConstant.SECONDS_PER_MINUTE);
        StringBuilder buf = new StringBuilder(24);
        buf.append(days).append("天");
        buf.append(hours).append("小时");
        buf.append(minutes).append("分钟");
        buf.append(seconds).append("秒");
        return buf.toString();
    }

    /**
     * 将秒转为时间格式
     * @param seconds
     * @return
     */
    public static String seconds2Time(int seconds) {
        int dialSeconds = seconds;
        int dialhous = dialSeconds / 3600;
        int dialMinutes = dialSeconds / 60 % 60;
        dialSeconds %= 60;
        String showMintues = "";
        String showSeconds = "";
        String showText = "";
        if (dialSeconds < 10) {
            showSeconds = "0" + dialSeconds;
        } else {
            showSeconds = Integer.toString(dialSeconds);
        }
        if (dialMinutes < 10) {
            showMintues = "0" + dialMinutes;
        } else {
            showMintues = Integer.toString(dialMinutes);
        }
        if (dialhous > 0) {
            showText = dialhous + ":" + showMintues + ":" + showSeconds;
        } else {
            showText = showMintues + ":" + showSeconds;
        }
        return showText;
    }

    public static void main(String[] args) {
        System.out.println(seconds2Time(31535812));
    }

    /**
     * 出生年月日计算年龄
     * */
    public static int getAge(Date birth) {
        Calendar cal = Calendar.getInstance();
        int thisYear = cal.get(Calendar.YEAR);
        int thisMonth = cal.get(Calendar.MONTH);
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birth);
        int birthYear = cal.get(Calendar.YEAR);
        int birthMonth = cal.get(Calendar.MONTH);
        int birthdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);

        int age = thisYear - birthYear;

        // 未足月
        if (thisMonth <= birthMonth) {
            // 当月
            if (thisMonth == birthMonth) {
                // 未足日
                if (dayOfMonth < birthdayOfMonth) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return age;
    }


}

